package com.auctionhaus
import grails.converters.*

class CustomerController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def xmlList = {
        def tempC = Customer.findByLoginNameIlike(params.itemName)
         if (tempC) {
              def list = Listing.findBySeller(tempC)

              render(contentType:"text/xml"){
                  customer(loginName:tempC.loginName, emailAddress:tempC.emailAddress){
                      listings{
                          for(a in list){
                              listing(listName:a.listName){
                                link("/rws/listing/$a.listName")
                              }
                          }
                      }
                  }
              }
          }
          else allCustomersAsXML()
    }

     def allCustomersAsXML = {
         def list = Customer.list()
         render(contentType:"text/xml"){
             customers{
                 for(a in list){
                     customer(loginName:a.loginName, emailAddress:a.emailAddress)
                 }
             }
         }
     }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [customerInstanceList: Customer.list(params), customerInstanceTotal: Customer.count()]
    }

    // Requirement S-5
    def myListings = {
        if(session?.customer)
        {
            def customerInstance = Customer.findById(session.customer.getId())

            if (!customerInstance) {
                flash.message = "Error in login!"
                redirect(action: "list")
            }

            [customerInstanceList: Customer.findByEmailAddressIlike(customerInstance.emailAddress).listings, customerInstanceListingTotal: customerInstance.listings.size(), customerInstance:customerInstance]
        }
        else{
            flash.message = "User not logged in!"
            redirect(action: 'create')
        }
    }

    def hasRole(principal, roleName){
        def customer = Customer.findByEmailAddress(principal, [fetch:[roles:'join']])
        return customer.roles.any {it.name == RoleName.valueOf(roleName)}
    }

    def register = {
        if(request.method == 'POST'){
            def customerInstance = new Customer(params)
            customerInstance.adminRole = params.adminRole ? params.adminRole : false;
            if(!customerInstance.save())
            {
                return [customerInstance:customerInstance]
            }else{
                session.customer = customerInstance
                redirect(action: "create")
            }
        }else{
            redirect(action: "create")
        }
    }

    def auth = {
       if(params.emailAddress == 'Admin' && params.password == 'superuser'){
            flash.message = 'Admin'
       }
    }

    def login = {
        if(request.method == 'POST'){

            def customerInstance = Customer.findByEmailAddressIlike(params.emailAddress)

            if(customerInstance){
                if (params.password == customerInstance.password) {
                    session.customer = customerInstance
                    redirect(action:'myListings')
                }
                else{
                    flash.message = "Invalid Password"
                }
            }else {
                if (params.emailAddress)
                    flash.message = "Customer with email Address: " +  params.emailAddress + " not found."
                else
                    flash.message = "Login unsuccessful"
            }
        }
        render(view:"create")
    }

    // Logout works but the redirection is wrong....
    def logout = {
        session.customer = null
        redirect(controller: 'listing')
    }

    def create = {
        def customerInstance = new Customer()
        customerInstance.properties = params
        return [customerInstance: customerInstance]
    }

    def save = {
        params.date = (params.date ? params.date : new Date())
        def customerInstance = new Customer(params)
        if (customerInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'customer.label', default: 'Customer'), customerInstance.id])}"
            redirect(action: "show", id: customerInstance.id)
        }
        else {
            render(view: "create", model: [customerInstance: customerInstance])
        }
    }

    def show = {
        def customerInstance = Customer.get(params.id)
        if (!customerInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'customer.label', default: 'Customer'), params.id])}"
            redirect(action: "list")
        }
        else {
             withFormat {
                html customerInstance: customerInstance
                xml { render customerInstance as XML}
            }
        }
    }

    def edit = {
        if(request.method == 'POST')
        {
            def customer = new Customer(params)
            if(customer.hasErrors()){
                println 'errors'
                println customer.errors.allErrors
            }
        }

        def customerInstance = Customer.get(params.id)
        if (!customerInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'customer.label', default: 'Customer'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [customerInstance: customerInstance]
        }
    }

    def update = {
        def customerInstance = Customer.get(params.id)
        if (customerInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (customerInstance.version > version) {
                    
                    customerInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'customer.label', default: 'Customer')] as Object[], "Another user has updated this Customer while you were editing")
                    render(view: "edit", model: [customerInstance: customerInstance])
                    return
                }
            }
            customerInstance.properties = params
            if (!customerInstance.hasErrors() && customerInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'customer.label', default: 'Customer'), customerInstance.id])}"
                redirect(action: "show", id: customerInstance.id)
            }
            else {
                render(view: "edit", model: [customerInstance: customerInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'customer.label', default: 'Customer'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def customerInstance = Customer.get(params.id)
        if (customerInstance) {
            try {
                if(customerInstance.emailAddress == 'admin@admin.com'){
                    // Delete check for Assignment #2   C4
                    // do not delete admin customer.
                    flash.message = "Cannot delete the default admin user!"
                    redirect(action: "show", id: params.id)
                    println "unable to delete default admin"
                }
                else if(customerInstance.listings?.size() > 0){
                    // Delete check for Assignment #2   C4
                    // do not delete if customer has listings
                    // redirect to customer
                    flash.message = "Cannot delete a customer with a listing!"
                    redirect(action: "show", id: params.id)
                    println "unable to delete customer with a listing"
                } else if (customerInstance.bid?.size() > 0){
                     // Delete check for Assignment #2 C4
                    // do not delete if customer has listings
                    // redirect to customer
                    flash.message = "Cannot delete a customer with a bid!"
                    redirect(action: "show", id: params.id)
                    println "unable to delete customer with a bid"
                }
                else {
                    customerInstance.delete(flush: true)
                    flash.message = "Deleting customer ${params.id}"
                    redirect(action: "list")
                    println "delete"
                }

            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Error in call to delete customer ${params.id}"
                redirect(action: "show", id: params.id)
                println "error in delete"
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'customer.label', default: 'Customer'), params.id])}"
            redirect(action: "list")
            println "No customer instance delete"
        }
    }

//    def login = { //LoginCommand cmd ->
//        if (request.method == 'POST') {
//            if (!cmd.hasErrors()) {
//                session.user = cmd.getUser()
//                redirect(controller:'listing')
//            }
//            else {
//                render(view: '/listing/index', model:[loginCmd:cmd])
//            }
//        }
//        else {
//            render(view:'/listing/index')
//        }
//
//    }
}
